import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import './assets/styles/main.scss'
import { useUserStore } from './stores/user'

// 自定义权限指令
import permissionDirective from './utils/permission'

const app = createApp(App)
const pinia = createPinia()
app.use(pinia)

// 权限指令
app.directive('permission', {
  mounted(el, binding) {
    const userStore = useUserStore()
    const permissionValue = binding.value

    // 验证值类型
    if (typeof permissionValue === 'string') {
      // 单一权限验证
      if (!userStore.hasPermission(permissionValue)) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else if (Array.isArray(permissionValue)) {
      // 权限数组，检查是否拥有任一权限
      const hasPermission = userStore.hasAnyPermission(permissionValue)
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else if (typeof permissionValue === 'object') {
      // 对象形式，可以指定 all: true 表示需要全部权限
      const { all, permissions } = permissionValue
      const hasPermission = all 
        ? userStore.hasAllPermissions(permissions) 
        : userStore.hasAnyPermission(permissions)
      
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
})

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 注册自定义权限指令
app.directive('permission', permissionDirective)

app.use(router)
app.use(ElementPlus, { 
  size: 'default', 
  zIndex: 3000,
  locale: zhCn 
})

app.mount('#app')